package com.team9.fitness.service;

import com.team9.fitness.dto.SignInDTO;
import com.team9.fitness.dto.SignUpDTO;
import com.team9.fitness.entity.User;
import com.team9.fitness.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.team9.fitness.entity.UserProfile;
import java.time.LocalDate;

/**
 * 用户管理服务类
 * 
 * 提供用户注册、登录、查询等核心业务逻辑
 * 支持用户名唯一性验证和密码验证
 */
@Service
public class UserService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserProfileService userProfileService;

    /**
     * 用户登录
     */
    public ResponseEntity<Map<String, Object>> signIn(SignInDTO signInDTO) {
        Map<String, Object> response = new HashMap<>();

        // 参数验证
        String validationMessage = signInVerify(signInDTO);
        if (validationMessage != null) {
            response.put("success", false);
            response.put("message", validationMessage);
            return ResponseEntity.badRequest().body(response);
        }

        // 查询用户
        Long count = userMapper.judge(signInDTO.getUsername(), signInDTO.getPassword());

        if (count > 0) {
            // 获取用户信息
            User user = userMapper.selectByUsername(signInDTO.getUsername());

            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
            return ResponseEntity.ok(response); // 返回200状态码，让前端根据success字段判断
        }
    }

    /**
     * 用户注册
     */
    public ResponseEntity<Map<String, Object>> signUp(SignUpDTO signUpDTO) {
        Map<String, Object> response = new HashMap<>();

        // 参数验证
        String validationMessage = signUpVerify(signUpDTO);
        if (validationMessage != null) {
            response.put("success", false);
            response.put("message", validationMessage);
            return ResponseEntity.badRequest().body(response);
        }

        // 检查用户名是否已存在
        Long existingCount = userMapper.countByUsername(signUpDTO.getUsername());
        if (existingCount > 0) {
            response.put("success", false);
            response.put("message", "用户名已存在");
            return ResponseEntity.ok(response); // 返回200状态码，让前端根据success字段判断
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(signUpDTO.getUsername());
        newUser.setPassword(signUpDTO.getPassword());

        try {
            userMapper.insert(newUser);
            User savedUser = newUser;

            response.put("success", true);
            response.put("message", "注册成功");
            response.put("user", savedUser);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "注册失败：" + e.getMessage());
            return ResponseEntity.ok(response); // 返回200状态码，让前端根据success字段判断
        }
    }

    /**
     * 登录参数验证
     */
    private String signInVerify(SignInDTO signInDTO) {
        if (signInDTO == null) {
            return "登录信息不能为空";
        }
        if (!StringUtils.hasText(signInDTO.getUsername())) {
            return "用户名不能为空";
        }
        if (!StringUtils.hasText(signInDTO.getPassword())) {
            return "密码不能为空";
        }
        if (signInDTO.getUsername().length() > 20) {
            return "用户名长度不能超过20个字符";
        }
        if (signInDTO.getPassword().length() < 6 || signInDTO.getPassword().length() > 20) {
            return "密码长度必须在6到20个字符之间";
        }
        return null; // 验证通过返回null
    }

    /**
     * 注册参数验证
     */
    private String signUpVerify(SignUpDTO signUpDTO) {
        if (signUpDTO == null) {
            return "注册信息不能为空";
        }
        if (!StringUtils.hasText(signUpDTO.getUsername())) {
            return "用户名不能为空";
        }
        if (!StringUtils.hasText(signUpDTO.getPassword())) {
            return "密码不能为空";
        }
        if (!StringUtils.hasText(signUpDTO.getConfirmPassword())) {
            return "确认密码不能为空";
        }
        if (!signUpDTO.getPassword().equals(signUpDTO.getConfirmPassword())) {
            return "两次输入的密码不一致";
        }
        if (signUpDTO.getUsername().length() > 20) {
            return "用户名长度不能超过20个字符";
        }
        if (signUpDTO.getPassword().length() < 6 || signUpDTO.getPassword().length() > 20) {
            return "密码长度必须在6到20个字符之间";
        }
        return null; // 验证通过返回null
    }

    /**
     * 根据用户名查找用户
     */
    public ResponseEntity<Map<String, Object>> getUserByUsername(String username) {
        Map<String, Object> response = new HashMap<>();

        if (!StringUtils.hasText(username)) {
            response.put("success", false);
            response.put("message", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        User user = userMapper.selectByUsername(username);
        if (user != null) {
            response.put("success", true);
            response.put("user", user);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.ok(response); // 返回200状态码，让前端根据success字段判断
        }
    }

    /**
     * 用户登录业务逻辑（供ZRDDS调用）
     */
    public User loginUser(String username, String password) {
        try {
            // 参数验证
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                log.warn("登录参数验证失败: username={}", username);
                return null;
            }

            // 查询用户
            Long count = userMapper.judge(username, password);
            if (count > 0) {
                User user = userMapper.selectByUsername(username);
                log.info("用户登录成功: userId={}, username={}", user.getId(), username);
                return user;
            } else {
                log.warn("用户名或密码错误: username={}", username);
                return null;
            }
        } catch (Exception e) {
            log.error("用户登录失败: username={}", username, e);
            return null;
        }
    }

    /**
     * 用户注册业务逻辑（供ZRDDS调用）
     */
    public User registerUser(String username, String password) {
        try {
            // 参数验证
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                log.warn("注册参数验证失败: username={}", username);
                return null;
            }

            // 检查用户名是否已存在
            Long existingCount = userMapper.countByUsername(username);
            if (existingCount > 0) {
                log.warn("用户名已存在: username={}", username);
                return null;
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);

            userMapper.insert(newUser);
            log.info("用户注册成功: userId={}, username={}", newUser.getId(), username);
            return newUser;
        } catch (Exception e) {
            log.error("用户注册失败: username={}", username, e);
            return null;
        }
    }

    /**
     * 更新用户资料业务逻辑（供ZRDDS调用）
     */
    public UserProfile updateUserProfile(Long userId, String height, String weight, String gender, String birthday) {
        try {
            // 检查用户是否存在
            User user = userMapper.selectById(userId);
            if (user == null) {
                log.warn("用户不存在: userId={}", userId);
                return null;
            }

            // 获取或创建用户资料
            UserProfile profile = userProfileService.getUserProfileByUserId(userId);
            if (profile == null) {
                profile = new UserProfile();
                profile.setUserId(userId);
            }

            // 更新资料
            if (height != null && !height.isEmpty()) {
                try {
                    profile.setHeight(Double.parseDouble(height));
                } catch (NumberFormatException e) {
                    log.warn("身高格式错误: {}", height);
                }
            }
            if (weight != null && !weight.isEmpty()) {
                try {
                    profile.setWeight(Double.parseDouble(weight));
                } catch (NumberFormatException e) {
                    log.warn("体重格式错误: {}", weight);
                }
            }
            profile.setGender(gender);
            if (birthday != null && !birthday.isEmpty()) {
                try {
                    profile.setBirthday(LocalDate.parse(birthday));
                } catch (Exception e) {
                    log.warn("生日格式错误: {}", birthday);
                }
            }

            // 保存资料
            userProfileService.saveOrUpdateUserProfile(profile);

            log.info("用户资料更新成功: userId={}", userId);
            return profile;
        } catch (Exception e) {
            log.error("用户资料更新失败: userId={}", userId, e);
            return null;
        }
    }

}
